import android.os.Build.VERSION_CODES.O
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer

object LiveEventBus {
    private val eventMap = mutableMapOf<String, MutableLiveData<Any>>()

    // 获取 MutableLiveData 实例
    @Suppress("UNCHECKED_CAST")
    private fun <T> getMutableLiveData(key: String): MutableLiveData<T> {
        if (!eventMap.containsKey(key)) {
            eventMap[key] = MutableLiveData()
        }
        return eventMap[key] as MutableLiveData<T>
    }

    // 发送事件
    fun <T> post(key: String, data: T) {
        getMutableLiveData<T>(key).value = data
    }

    // 观察事件
    fun <T> observe(key: String, owner: LifecycleOwner, observer: Observer<in T>) {
        getMutableLiveData<T>(key).observe(owner, observer)
    }
}

// 发送事件
inline fun <reified T> sendLiveEventData(key: String, data: T) {
    LiveEventBus.post(key, data)
}

// 接收事件
inline fun <reified T> LifecycleOwner.observeLiveEvent(
    key: String,
    noinline listener: (data: T) -> Unit
) {
    val observer = Observer<T> { data ->
        listener.invoke(data)
    }
    LiveEventBus.observe(key, this, observer)
}